const fs = require("fs");
const cheerio = require("cheerio");
const superagent = require("superagent");
const moment = require("moment");
const path = require("path");

const huilvURL = "https://huilv.91guzhi.com/";
let num3 = 0;
function getDailyFXJson() {
  superagent.get(huilvURL, (err, res) => {
    if (err) console.error(err);
    const $ = cheerio.load(res.text);
    let $tittle = $("#main .left .box .sinfo").children().eq(2);
    let $time = $("#main .left .box .sinfo").children().eq(3);
    let tittle = $tittle.text();
    tittle = Number(tittle.split("：")[1]);
    let time = $time.text();
    time = time.split("：")[1];
    let id = Date.now();
    let newsList = {
      id: id,
      USDCNY: tittle,
      time: time,
    };

    writeJson(newsList);

    //写入模块
    function writeJson(params) {
      //现将json文件读出来
      fs.readFile(
        path.join("../jsonserver/DataBase/DailyhuilvSearch.json"),
        function (err, data) {
          if (err) {
            return console.error(err);
          }
          var p1 = data.toString(); //将二进制的数据转换为字符串
          var p = JSON.parse(p1); //将字符串转换为json对象
          p.data.push(params); //将传来的对象push进数组对象中
          p.total = p.data.length; //定义一下总条数，为以后的分页打基础
          var str = JSON.stringify(p); //因为nodejs的写入文件只认识字符串或者二进制数，所以把json对象转换成字符串重新写入json文件中
          fs.writeFile(
            path.join("../jsonserver/DataBase/DailyhuilvSearch.json"),
            str,
            function (err) {
              if (err) {
                console.error(err);
              }
              num3++;
              let current_time = moment(Date.now()).format(
                "YYYY-MM-DD HH:mm:ss"
              );
              console.log(
                "ExchangeRange爬取次数：" + num3 + " |time：" + current_time
              );
            }
          );
        }
      );
    }
  });
}
//汇率爬虫模块-end

//定时爬取
function toGet() {
  setInterval(getDailyFXJson, 180000);
}

module.exports.exchangeRange = toGet;
